API:
[lhc/web/wiklou.git] / includes / api / ApiPageSet.php
1 <?php
2
3 /*
4 * Created on Sep 24, 2006
5 *
6 * API for MediaWiki 1.8+
7 *
8 * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23 * http://www.gnu.org/copyleft/gpl.html
24 */
25
26 if (!defined('MEDIAWIKI')) {
27 // Eclipse helper - will be ignored in production
28 require_once ('ApiQueryBase.php');
29 }
30
31 /**
32 * This class contains a list of pages that the client has requested.
33 * Initially, when the client passes in titles=, pageids=, or revisions= parameter,
34 * an instance of the ApiPageSet class will normalize titles,
35 * determine if the pages/revisions exist, and prefetch any additional data page data requested.
36 *
37 * When generator is used, the result of the generator will become the input for the
38 * second instance of this class, and all subsequent actions will go use the second instance
39 * for all their work.
40 *
41 * @addtogroup API
42 */
43 class ApiPageSet extends ApiQueryBase {
44
45 private $mAllPages; // [ns][dbkey] => page_id or 0 when missing
46 private $mTitles, $mGoodTitles, $mMissingTitles, $mMissingPageIDs, $mRedirectTitles;
47 private $mNormalizedTitles, $mInterwikiTitles;
48 private $mResolveRedirects, $mPendingRedirectIDs;
49 private $mGoodRevIDs, $mMissingRevIDs;
50 private $mFakePageId;
51
52 private $mRequestedPageFields;
53
54 public function __construct($query, $resolveRedirects = false) {
55 parent :: __construct($query, __CLASS__);
56
57 $this->mAllPages = array ();
58 $this->mTitles = array();
59 $this->mGoodTitles = array ();
60 $this->mMissingTitles = array ();
61 $this->mMissingPageIDs = array ();
62 $this->mRedirectTitles = array ();
63 $this->mNormalizedTitles = array ();
64 $this->mInterwikiTitles = array ();
65 $this->mGoodRevIDs = array();
66 $this->mMissingRevIDs = array();
67
68 $this->mRequestedPageFields = array ();
69 $this->mResolveRedirects = $resolveRedirects;
70 if($resolveRedirects)
71 $this->mPendingRedirectIDs = array();
72
73 $this->mFakePageId = -1;
74 }
75
76 public function isResolvingRedirects() {
77 return $this->mResolveRedirects;
78 }
79
80 public function requestField($fieldName) {
81 $this->mRequestedPageFields[$fieldName] = null;
82 }
83
84 public function getCustomField($fieldName) {
85 return $this->mRequestedPageFields[$fieldName];
86 }
87
88 /**
89 * Get fields that modules have requested from the page table
90 */
91 public function getPageTableFields() {
92 // Ensure we get minimum required fields
93 $pageFlds = array (
94 'page_id' => null,
95 'page_namespace' => null,
96 'page_title' => null
97 );
98
99 // only store non-default fields
100 $this->mRequestedPageFields = array_diff_key($this->mRequestedPageFields, $pageFlds);
101
102 if ($this->mResolveRedirects)
103 $pageFlds['page_is_redirect'] = null;
104
105 $pageFlds = array_merge($pageFlds, $this->mRequestedPageFields);
106 return array_keys($pageFlds);
107 }
108
109 /**
110 * Returns an array [ns][dbkey] => page_id for all requested titles
111 * page_id is a unique negative number in case title was not found
112 */
113 public function getAllTitlesByNamespace() {
114 return $this->mAllPages;
115 }
116
117 /**
118 * All Title objects provided.
119 * @return array of Title objects
120 */
121 public function getTitles() {
122 return $this->mTitles;
123 }
124
125 /**
126 * Returns the number of unique pages (not revisions) in the set.
127 */
128 public function getTitleCount() {
129 return count($this->mTitles);
130 }
131
132 /**
133 * Title objects that were found in the database.
134 * @return array page_id (int) => Title (obj)
135 */
136 public function getGoodTitles() {
137 return $this->mGoodTitles;
138 }
139
140 /**
141 * Returns the number of found unique pages (not revisions) in the set.
142 */
143 public function getGoodTitleCount() {
144 return count($this->mGoodTitles);
145 }
146
147 /**
148 * Title objects that were NOT found in the database.
149 * The array's index will be negative for each item
150 * @return array of Title objects
151 */
152 public function getMissingTitles() {
153 return $this->mMissingTitles;
154 }
155
156 /**
157 * Page IDs that were not found in the database
158 * @return array of page IDs
159 */
160 public function getMissingPageIDs() {
161 return $this->mMissingPageIDs;
162 }
163
164 /**
165 * Get a list of redirects when doing redirect resolution
166 * @return array prefixed_title (string) => prefixed_title (string)
167 */
168 public function getRedirectTitles() {
169 return $this->mRedirectTitles;
170 }
171
172 /**
173 * Get a list of title normalizations - maps the title given
174 * with its normalized version.
175 * @return array raw_prefixed_title (string) => prefixed_title (string)
176 */
177 public function getNormalizedTitles() {
178 return $this->mNormalizedTitles;
179 }
180
181 /**
182 * Get a list of interwiki titles - maps the title given
183 * with to the interwiki prefix.
184 * @return array raw_prefixed_title (string) => interwiki_prefix (string)
185 */
186 public function getInterwikiTitles() {
187 return $this->mInterwikiTitles;
188 }
189
190 /**
191 * Get the list of revision IDs (requested with revids= parameter)
192 * @return array revID (int) => pageID (int)
193 */
194 public function getRevisionIDs() {
195 return $this->mGoodRevIDs;
196 }
197
198 /**
199 * Revision IDs that were not found in the database
200 * @return array of revision IDs
201 */
202 public function getMissingRevisionIDs() {
203 return $this->mMissingRevIDs;
204 }
205
206 /**
207 * Returns the number of revisions (requested with revids= parameter)
208 */
209 public function getRevisionCount() {
210 return count($this->getRevisionIDs());
211 }
212
213 /**
214 * Populate from the request parameters
215 */
216 public function execute() {
217 $this->profileIn();
218 $titles = $pageids = $revids = null;
219 extract($this->extractRequestParams());
220
221 // Only one of the titles/pageids/revids is allowed at the same time
222 $dataSource = null;
223 if (isset ($titles))
224 $dataSource = 'titles';
225 if (isset ($pageids)) {
226 if (isset ($dataSource))
227 $this->dieUsage("Cannot use 'pageids' at the same time as '$dataSource'", 'multisource');
228 $dataSource = 'pageids';
229 }
230 if (isset ($revids)) {
231 if (isset ($dataSource))
232 $this->dieUsage("Cannot use 'revids' at the same time as '$dataSource'", 'multisource');
233 $dataSource = 'revids';
234 }
235
236 switch ($dataSource) {
237 case 'titles' :
238 $this->initFromTitles($titles);
239 break;
240 case 'pageids' :
241 $this->initFromPageIds($pageids);
242 break;
243 case 'revids' :
244 if($this->mResolveRedirects)
245 $this->dieUsage('revids may not be used with redirect resolution', 'params');
246 $this->initFromRevIDs($revids);
247 break;
248 default :
249 // Do nothing - some queries do not need any of the data sources.
250 break;
251 }
252 $this->profileOut();
253 }
254
255 /**
256 * Initialize PageSet from a list of Titles
257 */
258 public function populateFromTitles($titles) {
259 $this->profileIn();
260 $this->initFromTitles($titles);
261 $this->profileOut();
262 }
263
264 /**
265 * Initialize PageSet from a list of Page IDs
266 */
267 public function populateFromPageIDs($pageIDs) {
268 $this->profileIn();
269 $this->initFromPageIds($pageIDs);
270 $this->profileOut();
271 }
272
273 /**
274 * Initialize PageSet from a rowset returned from the database
275 */
276 public function populateFromQueryResult($db, $queryResult) {
277 $this->profileIn();
278 $this->initFromQueryResult($db, $queryResult);
279 $this->profileOut();
280 }
281
282 /**
283 * Initialize PageSet from a list of Revision IDs
284 */
285 public function populateFromRevisionIDs($revIDs) {
286 $this->profileIn();
287 $revIDs = array_map('intval', $revIDs); // paranoia
288 $this->initFromRevIDs($revIDs);
289 $this->profileOut();
290 }
291
292 /**
293 * Extract all requested fields from the row received from the database
294 */
295 public function processDbRow($row) {
296
297 // Store Title object in various data structures
298 $title = Title :: makeTitle($row->page_namespace, $row->page_title);
299
300 // skip any pages that user has no rights to read
301 if ($title->userCanRead()) {
302
303 $pageId = intval($row->page_id);
304 $this->mAllPages[$row->page_namespace][$row->page_title] = $pageId;
305 $this->mTitles[] = $title;
306
307 if ($this->mResolveRedirects && $row->page_is_redirect == '1') {
308 $this->mPendingRedirectIDs[$pageId] = $title;
309 } else {
310 $this->mGoodTitles[$pageId] = $title;
311 }
312
313 foreach ($this->mRequestedPageFields as $fieldName => & $fieldValues)
314 $fieldValues[$pageId] = $row-> $fieldName;
315 }
316 }
317
318 public function finishPageSetGeneration() {
319 $this->profileIn();
320 $this->resolvePendingRedirects();
321 $this->profileOut();
322 }
323
324 /**
325 * This method populates internal variables with page information
326 * based on the given array of title strings.
327 *
328 * Steps:
329 * #1 For each title, get data from `page` table
330 * #2 If page was not found in the DB, store it as missing
331 *
332 * Additionally, when resolving redirects:
333 * #3 If no more redirects left, stop.
334 * #4 For each redirect, get its links from `pagelinks` table.
335 * #5 Substitute the original LinkBatch object with the new list
336 * #6 Repeat from step #1
337 */
338 private function initFromTitles($titles) {
339
340 // Get validated and normalized title objects
341 $linkBatch = $this->processTitlesArray($titles);
342 if($linkBatch->isEmpty())
343 return;
344
345 $db = $this->getDB();
346 $set = $linkBatch->constructSet('page', $db);
347
348 // Get pageIDs data from the `page` table
349 $this->profileDBIn();
350 $res = $db->select('page', $this->getPageTableFields(), $set, __METHOD__);
351 $this->profileDBOut();
352
353 // Hack: get the ns:titles stored in array(ns => array(titles)) format
354 $this->initFromQueryResult($db, $res, $linkBatch->data, true); // process Titles
355
356 // Resolve any found redirects
357 $this->resolvePendingRedirects();
358 }
359
360 private function initFromPageIds($pageids) {
361 if(empty($pageids))
362 return;
363
364 $pageids = array_map('intval', $pageids); // paranoia
365 $set = array (
366 'page_id' => $pageids
367 );
368
369 $db = $this->getDB();
370
371 // Get pageIDs data from the `page` table
372 $this->profileDBIn();
373 $res = $db->select('page', $this->getPageTableFields(), $set, __METHOD__);
374 $this->profileDBOut();
375
376 $this->initFromQueryResult($db, $res, array_flip($pageids), false); // process PageIDs
377
378 // Resolve any found redirects
379 $this->resolvePendingRedirects();
380 }
381
382 /**
383 * Iterate through the result of the query on 'page' table,
384 * and for each row create and store title object and save any extra fields requested.
385 * @param $db Database
386 * @param $res DB Query result
387 * @param $remaining Array of either pageID or ns/title elements (optional).
388 * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
389 * @param $processTitles bool Must be provided together with $remaining.
390 * If true, treat $remaining as an array of [ns][title]
391 * If false, treat it as an array of [pageIDs]
392 * @return Array of redirect IDs (only when resolving redirects)
393 */
394 private function initFromQueryResult($db, $res, &$remaining = null, $processTitles = null) {
395 if (!is_null($remaining) && is_null($processTitles))
396 ApiBase :: dieDebug(__METHOD__, 'Missing $processTitles parameter when $remaining is provided');
397
398 while ($row = $db->fetchObject($res)) {
399
400 $pageId = intval($row->page_id);
401
402 // Remove found page from the list of remaining items
403 if (isset($remaining)) {
404 if ($processTitles)
405 unset ($remaining[$row->page_namespace][$row->page_title]);
406 else
407 unset ($remaining[$pageId]);
408 }
409
410 // Store any extra fields requested by modules
411 $this->processDbRow($row);
412 }
413 $db->freeResult($res);
414
415 if(isset($remaining)) {
416 // Any items left in the $remaining list are added as missing
417 if($processTitles) {
418 // The remaining titles in $remaining are non-existant pages
419 foreach ($remaining as $ns => $dbkeys) {
420 foreach ( $dbkeys as $dbkey => $unused ) {
421 $title = Title :: makeTitle($ns, $dbkey);
422 $this->mAllPages[$ns][$dbkey] = $this->mFakePageId;
423 $this->mMissingTitles[$this->mFakePageId] = $title;
424 $this->mFakePageId--;
425 $this->mTitles[] = $title;
426 }
427 }
428 }
429 else
430 {
431 // The remaining pageids do not exist
432 if(empty($this->mMissingPageIDs))
433 $this->mMissingPageIDs = array_keys($remaining);
434 else
435 $this->mMissingPageIDs = array_merge($this->mMissingPageIDs, array_keys($remaining));
436 }
437 }
438 }
439
440 private function initFromRevIDs($revids) {
441
442 if(empty($revids))
443 return;
444
445 $db = $this->getDB();
446 $pageids = array();
447 $remaining = array_flip($revids);
448
449 $tables = array('revision');
450 $fields = array('rev_id','rev_page');
451 $where = array('rev_deleted' => 0, 'rev_id' => $revids);
452
453 // Get pageIDs data from the `page` table
454 $this->profileDBIn();
455 $res = $db->select( $tables, $fields, $where, __METHOD__ );
456 while ( $row = $db->fetchObject( $res ) ) {
457 $revid = intval($row->rev_id);
458 $pageid = intval($row->rev_page);
459 $this->mGoodRevIDs[$revid] = $pageid;
460 $pageids[$pageid] = '';
461 unset($remaining[$revid]);
462 }
463 $db->freeResult( $res );
464 $this->profileDBOut();
465
466 $this->mMissingRevIDs = array_keys($remaining);
467
468 // Populate all the page information
469 if($this->mResolveRedirects)
470 ApiBase :: dieDebug(__METHOD__, 'revids may not be used with redirect resolution');
471 $this->initFromPageIds(array_keys($pageids));
472 }
473
474 private function resolvePendingRedirects() {
475
476 if($this->mResolveRedirects) {
477 $db = $this->getDB();
478 $pageFlds = $this->getPageTableFields();
479
480 // Repeat until all redirects have been resolved
481 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
482 while (!empty ($this->mPendingRedirectIDs)) {
483
484 // Resolve redirects by querying the pagelinks table, and repeat the process
485 // Create a new linkBatch object for the next pass
486 $linkBatch = $this->getRedirectTargets();
487
488 if ($linkBatch->isEmpty())
489 break;
490
491 $set = $linkBatch->constructSet('page', $db);
492 if(false === $set)
493 break;
494
495 // Get pageIDs data from the `page` table
496 $this->profileDBIn();
497 $res = $db->select('page', $pageFlds, $set, __METHOD__);
498 $this->profileDBOut();
499
500 // Hack: get the ns:titles stored in array(ns => array(titles)) format
501 $this->initFromQueryResult($db, $res, $linkBatch->data, true);
502 }
503 }
504 }
505
506 private function getRedirectTargets() {
507
508 $linkBatch = new LinkBatch();
509 $db = $this->getDB();
510
511 // find redirect targets for all redirect pages
512 $this->profileDBIn();
513 $res = $db->select('pagelinks', array (
514 'pl_from',
515 'pl_namespace',
516 'pl_title'
517 ), array (
518 'pl_from' => array_keys($this->mPendingRedirectIDs
519 )), __METHOD__);
520 $this->profileDBOut();
521
522 while ($row = $db->fetchObject($res)) {
523
524 $plfrom = intval($row->pl_from);
525
526 // Bug 7304 workaround
527 // ( http://bugzilla.wikipedia.org/show_bug.cgi?id=7304 )
528 // A redirect page may have more than one link.
529 // This code will only use the first link returned.
530 if (isset ($this->mPendingRedirectIDs[$plfrom])) { // remove line when bug 7304 is fixed
531
532 $titleStrFrom = $this->mPendingRedirectIDs[$plfrom]->getPrefixedText();
533 $titleStrTo = Title :: makeTitle($row->pl_namespace, $row->pl_title)->getPrefixedText();
534 unset ($this->mPendingRedirectIDs[$plfrom]); // remove line when bug 7304 is fixed
535
536 // Avoid an infinite loop by checking if we have already processed this target
537 if (!isset ($this->mAllPages[$row->pl_namespace][$row->pl_title])) {
538 $linkBatch->add($row->pl_namespace, $row->pl_title);
539 }
540 } else {
541 // This redirect page has more than one link.
542 // This is very slow, but safer until bug 7304 is resolved
543 $title = Title :: newFromID($plfrom);
544 $titleStrFrom = $title->getPrefixedText();
545
546 $article = new Article($title);
547 $text = $article->getContent();
548 $titleTo = Title :: newFromRedirect($text);
549 $titleStrTo = $titleTo->getPrefixedText();
550
551 if (is_null($titleStrTo))
552 ApiBase :: dieDebug(__METHOD__, 'Bug7304 workaround: redir target from {$title->getPrefixedText()} not found');
553
554 // Avoid an infinite loop by checking if we have already processed this target
555 if (!isset ($this->mAllPages[$titleTo->getNamespace()][$titleTo->getDBkey()])) {
556 $linkBatch->addObj($titleTo);
557 }
558 }
559
560 $this->mRedirectTitles[$titleStrFrom] = $titleStrTo;
561 }
562 $db->freeResult($res);
563
564 // All IDs must exist in the page table
565 if (!empty($this->mPendingRedirectIDs[$plfrom]))
566 ApiBase :: dieDebug(__METHOD__, 'Invalid redirect IDs were found');
567
568 return $linkBatch;
569 }
570
571 /**
572 * Given an array of title strings, convert them into Title objects.
573 * Alternativelly, an array of Title objects may be given.
574 * This method validates access rights for the title,
575 * and appends normalization values to the output.
576 *
577 * @return LinkBatch of title objects.
578 */
579 private function processTitlesArray($titles) {
580
581 $linkBatch = new LinkBatch();
582
583 foreach ($titles as $title) {
584
585 $titleObj = is_string($title) ? Title :: newFromText($title) : $title;
586 if (!$titleObj)
587 $this->dieUsage("bad title $titleString", 'invalidtitle');
588
589 $iw = $titleObj->getInterwiki();
590 if (!empty($iw)) {
591 // This title is an interwiki link.
592 $this->mInterwikiTitles[$titleObj->getPrefixedText()] = $iw;
593 } else {
594
595 // Validation
596 if ($titleObj->getNamespace() < 0)
597 $this->dieUsage("No support for special page $titleString has been implemented", 'unsupportednamespace');
598 if (!$titleObj->userCanRead())
599 $this->dieUsage("No read permission for $titleString", 'titleaccessdenied');
600
601 $linkBatch->addObj($titleObj);
602 }
603
604 // Make sure we remember the original title that was given to us
605 // This way the caller can correlate new titles with the originally requested,
606 // i.e. namespace is localized or capitalization is different
607 if (is_string($title) && $title !== $titleObj->getPrefixedText()) {
608 $this->mNormalizedTitles[$title] = $titleObj->getPrefixedText();
609 }
610 }
611
612 return $linkBatch;
613 }
614
615 protected function getAllowedParams() {
616 return array (
617 'titles' => array (
618 ApiBase :: PARAM_ISMULTI => true
619 ),
620 'pageids' => array (
621 ApiBase :: PARAM_TYPE => 'integer',
622 ApiBase :: PARAM_ISMULTI => true
623 ),
624 'revids' => array (
625 ApiBase :: PARAM_TYPE => 'integer',
626 ApiBase :: PARAM_ISMULTI => true
627 )
628 );
629 }
630
631 protected function getParamDescription() {
632 return array (
633 'titles' => 'A list of titles to work on',
634 'pageids' => 'A list of page IDs to work on',
635 'revids' => 'A list of revision IDs to work on'
636 );
637 }
638
639 public function getVersion() {
640 return __CLASS__ . ': $Id$';
641 }
642 }
643